from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render, redirect, get_object_or_404

# Create your views here.
from django.urls import reverse

from article.models import Article
from comment.forms import CommentForm


@login_required(login_url='bloguser:user_login')
def add_comment(request, id):
    article = get_object_or_404(Article, id=id)

    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.article = article
            new_comment.user = request.user
            new_comment.save()
            return redirect(reverse('article:article_detail', args=[int(id)]))
        else:
            return HttpResponse("表单内容有误，请重新填写。")

    # 处理错误请求
    else:
        return HttpResponse("发表评论仅接受POST请求。")
